package com.lx.pc.restful.wx;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.lx.pc.baidu.ueditor.define.FileType;
import com.lx.pc.domain.vo.supplycategory.SupplyCategoryVo;
import com.lx.pc.domain.vo.supplydemand.SupplydemandVo;
import com.lx.pc.domain.vo.supplydemandimg.SupplydemandimgVo;
import com.lx.pc.restful.util.AjaxResult;
import com.lx.pc.service.category.ICategoryService;
import com.lx.pc.service.supplycategory.ISupplyCategoryService;
import com.lx.pc.service.supplydemand.ISupplydemandService;
import com.lx.pc.service.supplydemandimg.ISupplydemandimgService;
import com.lx.pc.utils.ImageOperation;
import com.lx.pc.utils.OmsPage;

@Controller
@RequestMapping("/wx")
public class WxSupplyController {

	/**
	 * 求购黄页
	 */
	@Resource(name = "supplydemandService")
	private ISupplydemandService supplydemandService;

	/**
	 * 类目
	 */
	@Resource(name = "categoryService")
	private ICategoryService categoryService;

	/**
	 * 求购黄页图片
	 */
	@Resource(name = "supplydemandimgService")
	private ISupplydemandimgService supplydemandimgService;
	
	@Resource(name = "supplyCategoryService")
	private ISupplyCategoryService supplyCategoryService;

	/**
	 * 黄页类目
	 * 
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/toSupplyCategory.do")
	public String toSupplyCategory() {
		Map<String, Object> result = new HashMap<String, Object>();
		SupplyCategoryVo category = new SupplyCategoryVo();
		category.setParentId("0");
		category.setActive((short) 1);
		category.setStatus(1);
		// 一级类目
		List<SupplyCategoryVo> categoryList = supplyCategoryService.findByCategoryList(category);
		result.put("categoryList", categoryList);

		return JSON.toJSONString(result);
	}

	/**
	 * 黄页上传图片
	 * 
	 * @param v
	 * @param imgUrl
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/toUploadSupply.do")
	public String toUploadSupply(HttpServletRequest request, HttpServletResponse response) {

		Map<String, Object> result = new HashMap<String, Object>();

		// 获取文件需要上传到的路径
		String pathUrl = request.getSession().getServletContext().getRealPath("/") + ("fileImage/");

		System.out.println(pathUrl);
		String imgUrl = "";
		File dir = new File(pathUrl);
		if (!dir.exists()) {
			dir.mkdir();
		}

		// 获得磁盘文件条目工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// 如果没以下两行设置的话,上传大的文件会占用很多内存，
		// 设置暂时存放的存储室,这个存储室可以和最终存储文件的目录不同
		/**
		 * 原理: 它是先存到暂时存储室，然后再真正写到对应目录的硬盘上， 按理来说当上传一个文件时，其实是上传了两份，第一个是以 .tem 格式的
		 * 然后再将其真正写到对应目录的硬盘上
		 */
		factory.setRepository(dir);
		// 设置缓存的大小，当上传文件的容量超过该缓存时，直接放到暂时存储室
		factory.setSizeThreshold(1024 * 1024);
		// 高水平的API文件上传处理
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			request.setCharacterEncoding("utf-8"); // 设置编码
			List<FileItem> list = upload.parseRequest(request);
			// 多张图片
			FileItem picture = null;
			String userId = "";

			for (FileItem item : list) {
				// 如果获取的表单信息是普通的 文本 信息
				if (item.isFormField()) {
					// 获取用户具体输入的字符串
					userId = item.getString();
					System.out.println("userId------" + userId);
				} else {
					picture = item;
				}
			}
			// 获取文件名称
			String originFileName = picture.getName();
			System.out.println("------------" + originFileName);
			// 获取图片后缀
			String suffix = FileType.getSuffixByFilename(originFileName);
			// 重命名
			String targetFileName = (new Date()).getTime() + suffix;
			System.out.println("------------" + targetFileName);
			// 真正写到磁盘上
			File file = new File(pathUrl + targetFileName);
			imgUrl += targetFileName;

			OutputStream out = new FileOutputStream(file);
			InputStream in = picture.getInputStream();
			int length = 0;
			byte[] buf = new byte[1024];
			// in.read(buf) 每次读到的数据存放在buf 数组中
			while ((length = in.read(buf)) != -1) {
				// 在buf数组中取出数据写到（输出流）磁盘上
				out.write(buf, 0, length);
			}
			in.close();
			out.close();

		} catch (FileUploadException e1) {
		} catch (Exception e) {
		}
		result.put("imgUrl", imgUrl);
		return JSON.toJSONString(result);
	}

	/**
	 * 发布供需
	 * 
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/toSupplySave.do")
	public AjaxResult<String> toSupplySave(SupplydemandVo v, @RequestParam(value = "imgUrlStr[]") String[] imgUrlStr,
			HttpServletRequest request, HttpServletResponse response) {
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		String pathUrl = request.getSession().getServletContext().getRealPath("/") + ("fileImage/");
		if (v.getbId() != null) {
			SupplydemandimgVo vo = new SupplydemandimgVo();
			vo.setSupplyDemandId(v.getbId());
			List<SupplydemandimgVo> supplydemandimgVos = supplydemandimgService.findBySupplydemandimg(vo);
			for (SupplydemandimgVo vo2 : supplydemandimgVos) {
				supplydemandimgService.deleteSupplydemandimg(new BigInteger(vo2.getbId()));
			}

			SupplydemandVo supplydemandVo = supplydemandService.find(new BigInteger(v.getbId()));
			supplydemandVo.setCategoryId(v.getCategoryId());
			supplydemandVo.setContent(v.getContent());
			supplydemandVo.setProvince(v.getProvince());
			supplydemandVo.setCity(v.getCity());
			supplydemandVo.setContacts(v.getContacts());
			supplydemandVo.setTelephone(v.getTelephone());
			supplydemandVo.setType(v.getType());

			supplydemandService.updateSupplydemand(supplydemandVo);
			if (imgUrlStr != null) {
				for (String str : imgUrlStr) {
					System.out.println("imgUrlStr------" + str);
					String url = "";
					String urlImg = ImageOperation.getDomain(str);

					System.out.println("urlImg-----" + urlImg);
					if (urlImg.equals("zaishengwang.com")) {
						System.out.println("1url------");
						url = ImageOperation.uploadSupply(str.substring(str.lastIndexOf("/") + 1), pathUrl);
						System.out.println("1url------" + url);
					} else {
						// 从七牛下载图片到服务器
						ImageOperation.download(str, pathUrl);
						url = ImageOperation.uploadSupply(str.substring(str.lastIndexOf("/") + 1), pathUrl);
						System.out.println("2url------" + url);
					}

					SupplydemandimgVo supplydemandimgVo = new SupplydemandimgVo();
					supplydemandimgVo.setSupplyDemandId(v.getbId());
					supplydemandimgVo.setImg(str);
					supplydemandimgService.save(supplydemandimgVo);
				}
			}
		} else {
			supplydemandService.save(v);
			if (imgUrlStr != null) {
				for (int i = 0; i < imgUrlStr.length; i++) {
					String url = ImageOperation.uploadSupply(imgUrlStr[i].substring(imgUrlStr[i].lastIndexOf("/") + 1),
							pathUrl);
					System.out.println("------" + url);
					SupplydemandimgVo supplydemandimgVo = new SupplydemandimgVo();
					supplydemandimgVo.setSupplyDemandId(v.getId().toString());
					supplydemandimgVo.setImg(url);
					supplydemandimgService.save(supplydemandimgVo);
				}
			}
		}
		ajaxResult.setMsg("1");

		return ajaxResult;
	}

	/**
	 * 供需列表
	 * 
	 * @param v
	 * @param page
	 * @param size
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("/serchSupplyList")
	public String serchSupplyList(SupplydemandVo v, Integer page, Integer size) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		OmsPage<SupplydemandVo> pages = supplydemandService.findByWxSupplydemand(v, page, size);
		if (pages.getResult().size() > 0) {
			for (SupplydemandVo vo : pages.getResult()) {
				SupplydemandimgVo vo2 = new SupplydemandimgVo();
				vo2.setSupplyDemandId(vo.getbId());
				List<SupplydemandimgVo> supplydemandimgVo = supplydemandimgService.findBySupplydemandimg(vo2);
				vo.setSupplydemandimgVos(supplydemandimgVo);
			}
		}
		result.put("supplydemand", pages.getResult());
		result.put("pages", pages);
		return JSON.toJSONString(result);
	}

	/**
	 * 查询详情
	 * 
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/toSypplyById")
	public String toSypplyById(SupplydemandVo v) {
		Map<String, Object> result = new HashMap<String, Object>();
		SupplydemandVo supplydemandVo = supplydemandService.findByWxSupplydemandId(new BigInteger(v.getbId()));
		result.put("supplydemandVo", supplydemandVo);
		return JSON.toJSONString(result);
	}

	/**
	 * 删除供需
	 * 
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/toDeleteSupply")
	public String toDeleteSupply(SupplydemandVo v) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (v.getbId() != null) {
			v.setActive((short) 0);
			v.setId(new BigInteger(v.getbId()));
			supplydemandService.updateSupplydemand(v);
		}
		result.put("msg", "1");
		return JSON.toJSONString(result);
	}

}
